﻿using Coldairarrow.Business.IT;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.IT
{
    [Route("/IT/[controller]/[action]")]
    public class IT_RecordBookController : BaseApiController
    {
        #region DI

        public IT_RecordBookController(IIT_RecordBookBusiness iT_RecordBookBus, IOperator op)
        {
            _iT_RecordBookBus = iT_RecordBookBus;
            _Op = op;
        }

        IIT_RecordBookBusiness _iT_RecordBookBus { get; }

        IOperator _Op { get; }

        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<IT_RecordBook>> GetDataList(IT_RecordBookPageInput input)
        {
            return await _iT_RecordBookBus.GetDataListAsync(input);
        }
        /// <summary>
        /// 库存台账dto
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<IT_RecordBookDTO>> GetDataListAsyncDtoList(PageInput<IT_RecordBookConditionDTO> input)
        {
            return await _iT_RecordBookBus.GetDataListAsyncDtoList(input);
        }
        [HttpPost]
        public async Task<IT_RecordBook> GetTheData(IdInputDTO input)
        {
            return await _iT_RecordBookBus.GetTheDataAsync(input.id);
        }
        /// <summary>
        /// Pc获取库存台账列表
        /// </summary>
        /// <param name="input">seach</param>
        /// <returns></returns>

        [HttpPost]
        public async Task<PageResult<IT_RecordBookDtoList>> GetIT_RecordBookList(PageInput<IT_RecordBookDtoListSeach> input)
        {
            var Data = await _iT_RecordBookBus.GetIT_RecordBookList(input);
            return Data;
        }

        /// <summary>
        /// 库存台账导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetExportRecordBookList(string RefCode, string Type, string GoLocation, string MaterSeach) {
            PageInput<IT_RecordBookDtoListSeach> input = new PageInput<IT_RecordBookDtoListSeach>();
            input.Search.RefCode = RefCode;
            input.Search.Type = Type;
            input.Search.GoLocation = GoLocation;
            input.Search.MaterSeach = MaterSeach;
            var DataList = await _iT_RecordBookBus.GetIT_RecordBookList(input);
            HSSFWorkbook book = new HSSFWorkbook();
            ISheet s1 = book.CreateSheet("库存台账");
            IRow r1 = s1.CreateRow(0);
            r1.CreateCell(0).SetCellValue("关联单号");
            r1.CreateCell(1).SetCellValue("台账类型");
            r1.CreateCell(2).SetCellValue("原始仓库");
            r1.CreateCell(3).SetCellValue("原始货位");
            r1.CreateCell(4).SetCellValue("目标货位");
            r1.CreateCell(5).SetCellValue("物料");
            r1.CreateCell(6).SetCellValue("单位");
            r1.CreateCell(7).SetCellValue("数量");
            r1.CreateCell(8).SetCellValue("创建人");
            r1.CreateCell(9).SetCellValue("创建时间");
            for (int i=0;i<=DataList.Data.Count;i++) {
                IRow rt = s1.CreateRow(i + 1);
                rt.CreateCell(0).SetCellValue(DataList.Data[i].RefCode);
                rt.CreateCell(1).SetCellValue(DataList.Data[i].Type);
                rt.CreateCell(2).SetCellValue(DataList.Data[i].FromStorName);
                rt.CreateCell(3).SetCellValue(DataList.Data[i].FromLocalName);
                rt.CreateCell(4).SetCellValue(DataList.Data[i].ToLocalName);
                rt.CreateCell(5).SetCellValue(DataList.Data[i].MaterialName);
                rt.CreateCell(6).SetCellValue(DataList.Data[i].MeasureName);
                rt.CreateCell(7).SetCellValue(DataList.Data[i].Num.ToString());
                rt.CreateCell(8).SetCellValue(DataList.Data[i].ReallName);
                rt.CreateCell(9).SetCellValue(DataList.Data[i].CreateTime.ToString());
            }
            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("{0}\\CD{1}.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                book.Write(stream);
                byte[] buffer = stream.ToArray();
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("库存台账.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }

        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(IT_RecordBook data)
        {
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _iT_RecordBookBus.AddDataAsync(data);
            }
            else
            {
                await _iT_RecordBookBus.UpdateDataAsync(data);
            }
        }

        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _iT_RecordBookBus.DeleteDataAsync(ids);
        }
        /// <summary>
        /// 台账表期初数据导入
        /// </summary>
        /// <param name="file">台账表期初数据EXCEL</param>
        /// <returns></returns>
        //[HttpPost]
        //[NoCheckJWT]
        //public async Task<AjaxResult> Import(IFormFile file)
        //{
        //    string ReturnValue = string.Empty;
        //    //定义一个bool类型的变量用来做验证
        //    bool flag = true;
        //    try
        //    {
        //        string fileExt = Path.GetExtension(file.FileName).ToLower();
        //        //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
        //        var Data = new List<IT_RecordBook>();

        //        MemoryStream ms = new MemoryStream();
        //        file.CopyTo(ms);
        //        ms.Seek(0, SeekOrigin.Begin);
        //        IWorkbook book;
        //        if (fileExt == ".xlsx")
        //        {
        //            book = new XSSFWorkbook(ms);
        //        }
        //        else if (fileExt == ".xls")
        //        {
        //            book = new HSSFWorkbook(ms);
        //        }
        //        else
        //        {
        //            book = null;
        //        }
        //        ISheet sheet = book.GetSheetAt(0);

        //        int CountRow = sheet.LastRowNum + 1;//获取总行数

        //        if (CountRow - 1 == 0)
        //        {
        //            return Error("Excel列表数据项为空!");

        //        }
        //        #region 循环验证
        //        for (int i = 1; i < CountRow; i++)
        //        {
        //            //获取第i行的数据
        //            var row = sheet.GetRow(i);
        //            if (row != null)
        //            {
        //                //循环的验证单元格中的数据
        //                for (int j = 0; j < 2; j++)
        //                {
        //                    if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
        //                    {
        //                        flag = false;
        //                        ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。";
        //                    }
        //                }
        //            }
        //        }
        //        #endregion
        //        if (flag)
        //        {
        //            for (int i = 1; i < CountRow; i++)//
        //            {
        //                var row = sheet.GetRow(i);
        //                //实例化实体对象
        //                IT_RecordBook commodity = new IT_RecordBook();
        //                commodity.RefCode = row.GetCell(0).ToString().Trim();
        //                commodity.Type = row.GetCell(1).ToString().Trim();
        //                Data.Add(commodity);
        //            }
        //        }
        //        if (Data.Count > 0)
        //        {
        //            ReturnValue =  _iT_RecordBookBus.ImportAsync(Data).Result;
        //            return Success(ReturnValue);
        //        }
        //        if (!flag)
        //        {
        //            return Error(ReturnValue = "数据存在问题！" + ReturnValue);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ReturnValue = ex.Message;
        //        return Error(ReturnValue = "数据存在问题！" + ReturnValue);
        //    }
        //    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
        //}

        /// <summary>
        /// 台帐表信息表模板导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            //创建EXCEL工作薄
            IWorkbook workBook = new XSSFWorkbook();
            //创建sheet文件表
            ISheet sheet = workBook.CreateSheet("库存台帐");

            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                    DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("{0}\\CD{1}.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));

            #region 创建Excel表头
            //创建表头
            IRow header = sheet.CreateRow(0);
            ICell cell = header.CreateCell(0);
            cell.SetCellValue("相关单号");

            cell = header.CreateCell(1);
            cell.SetCellValue("台账类型");


            #endregion
            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.Write(stream);
                byte[] buffer = stream.ToArray();

                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("库存台账表_{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }
        #endregion
    }
}